package com.wangzhixuan.controller.admin;

import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.result.PageInfo;
import com.wangzhixuan.commons.result.Result;
import com.wangzhixuan.commons.result.Tree;
import com.wangzhixuan.model.Role;
import com.wangzhixuan.service.IRoleService;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @description：权限管理
 * @author：zhixuan.wang
 * @date：2015/10/1 14:51
 */
@Api(tags = "4. 权限管理")
@RestController
@RequestMapping("/admin/role")
public class RoleController extends BaseController {

    @Autowired
    private IRoleService roleService;

    /**
     * 权限列表
     *
     * @param page
     * @param rows
     * @param sort
     * @param order
     * @return
     */
    @GetMapping("/dataGrid")
    public Result<PageInfo<Role>> dataGrid(Integer page, Integer rows, String sort, String order) {
        PageInfo<Role> pageInfo = new PageInfo<>(page, rows, sort, order);
        roleService.selectDataGrid(pageInfo);
        return renderObj(pageInfo);
    }

    /**
     * 权限树
     *
     * @return
     */
    @GetMapping("/tree")
    public Result<List<Tree>> tree() {
        return renderObj(roleService.selectTree());
    }

    /**
     * 添加权限
     *
     * @param role
     * @return
     */
    @PutMapping("/add")
    public Result<String> add(@Valid Role role) {
        roleService.save(role);
        return renderSuccess("添加成功！");
    }

    /**
     * 删除权限
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete")
    public Result<String> delete(Long id) {
        roleService.removeById(id);
        return renderSuccess("删除成功！");
    }

    /**
     * 删除权限
     *
     * @param role
     * @return
     */
    @PostMapping("/edit")
    public Result<String> edit(@Valid Role role) {
        roleService.updateById(role);
        return renderSuccess("编辑成功！");
    }

    /**
     * 授权页面页面根据角色查询资源
     *
     * @param id
     * @return
     */
    @GetMapping("/findResourceIdListByRoleId")
    public Result<List<Long>> findResourceByRoleId(Long id) {
        List<Long> resources = roleService.selectResourceIdListByRoleId(id);
        return renderObj(resources);
    }

    /**
     * 授权
     *
     * @param id
     * @param resourceIds
     * @return
     */
    @RequiresRoles("admin")
    @PostMapping("/grant")
    public Result<String> grant(Long id, String resourceIds) {
        roleService.updateRoleResource(id, resourceIds);
        return renderSuccess("授权成功！");
    }

}
